package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    HttpSession session;

    //查找全部分类
    @Override
    public List<Category> findAll() {
        List<Category> categoryList = categoryMapper.findAll();
        return categoryList;
    }

    //添加分类
    @Override
    public void add(Category category) {
        //设置分类id
       // category.setId(IdUtil.createSnowflake(1,1).nextId());
       /* //设置创建时间
        category.setCreateTime(new Date());
        //设置修改时间
        category.setUpdateTime(new Date());
        //设置创建者id
        Employee employee = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
        category.setCreateUser(employee.getId());
        //设置修改者id
        category.setUpdateUser(employee.getId());*/
        categoryMapper.insert(category);

        //调用Mapper数据库
        //categoryMapper.add(category);
    }


    //修改分类
    @Override
    public void update(Category category) {
        //设置修改时间
        /*category.setUpdateTime(new Date());
        //设置修改者id
        Employee employee = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
        category.setUpdateUser(employee.getId());*/
        //categoryMapper.update(category);



        //调用Mapper数据库
        categoryMapper.updateById(category);
    }

    @Override
    public void delete(Long id) {
        //查看菜品里是否有分类id
       Integer dish = categoryMapper.countDishByCategoryId(id);
       if(dish > 0){
           //return ResultInfo.error("该分类下有菜品，无法删除！");
           throw new CustomException("该分类下有菜品，无法删除！");
       }
       //查看套餐里是否有分类id
       Integer setmeal = categoryMapper.countSetmealByCategoryId(id);
       if(setmeal > 0){
           //return ResultInfo.error("该分类下有套餐，无法删除");
           throw new CustomException("该分类下有套餐，无法删除");
       }

       categoryMapper.delete(id);
       //return ResultInfo.success();
    }

    //根据type从数据表查询分类列表
    @Override
    public List<Category> list(Integer type) {
        LambdaQueryWrapper<Category> clqw = new LambdaQueryWrapper<>();
        clqw.eq(Category::getType,type);
        return categoryMapper.selectList(clqw);
    }





}
